package handlers

import (
	"1-12zk/api/request"
	"1-12zk/api/response"
	"1-12zk/dao"
	"1-12zk/models"
	"1-12zk/util"
	"github.com/gin-gonic/gin"
	jwt "github.com/golangblogs/gojwt"
)

func Login(c *gin.Context) {
	var data request.Login
	if err := c.ShouldBind(&data); err != nil {
		response.ResponseError(c, err.Error())
		return
	}
	user, err := dao.GetUser(data.Phone)
	if err != nil {
		response.ResponseError(c, "查询失败")
		return
	}
	if user.Phone == "" {
		m := models.User{
			Phone:    data.Phone,
			Password: util.PwdMd5(data.Password),
		}
		err := dao.Create(m)
		if err != nil {
			response.ResponseError(c, "注册失败")
			return
		}
	}
	if user.Password != util.PwdMd5(data.Password) {
		response.ResponseError(c, "密码错误")
		return
	}
	claims := jwt.CustomClaims{ID: user.ID}
	token, err := jwt.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		response.ResponseError(c, "token生成失败")
		return
	}
	response.ResponseSuccess(c, token)
}
